//
//  PickNumSportViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-15.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddPickNumSportViewController.h"
#import "JddViewControllerManager.h"
#import "JddCommonFunction.h"
#import "JddDataParser.h"
#import "SBJson.h"
#import "FloatLayer.h"
@interface JddPickNumSportViewController (){
    NSInteger _floatLayerIndex;
    FloatLayer *_layer;
}

@end

@implementation JddPickNumSportViewController
@synthesize label2;
@synthesize label3;
@synthesize tempResult;
@synthesize Matchs;
@synthesize Matchtemp;
@synthesize count;

-(IBAction)sureSelect:(id)sender{
    if ([childTableview.sportlotterylist.sportList count] == 0
        && (lottId == LOTTERY_PLAY_METHOD_FOOTBALL_BF
            || lottId == LOTTERY_PLAY_METHOD_FOOTBALL_BQC
            || lottId == LOTTERY_PLAY_METHOD_FOOTBALL_ZJQ)) {
        [JddCommonFunction messageBoxWithMessage:@"请至少选择1场比赛"];
        return;
    }else if(lottId == LOTTERY_PLAY_METHOD_FOOTBALL && [childTableview.sportlotterylist.sportList count] == 0){
                [JddCommonFunction messageBoxWithMessage:@"请至少选择2场比赛"];
    }else if(lottId == LOTTERY_PLAY_METHOD_FOOTBALL && [childTableview.sportlotterylist.sportList count] == 1 && ((JddSportNumber*)([childTableview.sportlotterylist.sportList objectAtIndex:0])).isSingle == 0){
        [JddCommonFunction messageBoxWithMessage:@"请至少选择2场比赛"];
    }
    /*else if ([childTableview.sportlotterylist.sportList count]<2 && lottId != LOTTERY_PLAY_METHOD_FOOTBALL_BF) {
        [JddCommonFunction messageBoxWithMessage:@"请至少选择2场比赛"];
        return;
    }*/ else{
        if ([childTableview.sportlotterylist.sportList count]>0) {
            JddSportNumber *sportnum1 = [childTableview.sportlotterylist.sportList objectAtIndex:0];
            NSDate *date1 = [JddCommonFunction dateFromString:sportnum1.endTime]; 
            for (JddSportNumber *sportnum in childTableview.sportlotterylist.sportList) {
                NSDate *date2 = [JddCommonFunction dateFromString:sportnum.endTime];
                date1 =  [date2 earlierDate:date1];
            }
            NSArray *arr = [NSArray arrayWithObjects:date1, [NSNumber numberWithInt:lottId], nil];
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SPORT_LIST 
                                                                 fromController:self 
                                                                     withObject:childTableview.sportlotterylist.sportList
                                                                    withObject2:arr];
        }else{
            return;
        }
    }
}

-(void)listSelect{
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width) / 2.0;
//    rect.origin.y = (rect.size.height) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 300.0;
//    indexList = [JddIndexListView getInstanceView];
//    [indexList setFrame:rect];
//    indexList.type = 1;
//    indexList.delegate = self;
//    [indexList show];
    
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    noticeView.webInfoId = LOTTERY_TYPE_ID_JCZQ;
    [self.navigationController pushViewController:noticeView animated:YES];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.message isEqualToString:@"您还没有登录，请先登录"]) {
        if (buttonIndex == 0) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:
             CONTROLLER_LOGIN 
                                                                 fromController:self
                                                                     withObject:nil 
                                                                    withObject2:nil];
        }
    }
}

//-(void)selectorbutton1{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_SPORT_RESULT
//                                                         fromController:self 
//                                                             withObject:nil 
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton2{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ; 
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_BUY_HISTORY 
//                                                             fromController:self 
//                                                                 withObject:[NSNumber numberWithInt:LOTTERY_TYPE_ID_FOOTBALL]
//                                                                withObject2:nil];
//    }
//}
//
//-(void)selectorbutton3{
//    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_HOW_TO_PLAY_SSQ
//                                                         fromController:self 
//                                                             withObject:nil 
//                                                            withObject2:nil];
//}
//
//-(void)selectorbutton4{
//    if (![JddCommonFunction isLogin]) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"玩球球"
//                                                        message:@"您还没有登录，请先登录"
//                                                       delegate:self
//                                              cancelButtonTitle:@"确定"
//                                              otherButtonTitles:@"取消", nil]
//        ; 
//        [alert show];
//    }else {
//        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_FOLLOW_NUMBER_HISTORY 
//                                                             fromController:self 
//                                                                 withObject:nil 
//                                                                withObject2:nil];
//    }
//}
//- (void)backView
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (void)loadNavBar
{
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 40, 30);
    [right setTitle:@"帮助" forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:15];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(listSelect) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadNavBar];
    
    if (IOS7) {
         tView.frame = SPORT_CHILD_VIEW_FRAME;
    }else{
        tView.frame = CGRectMake(0, -20,SCREEN_WIDTH,  SCREEN_HEIGHT-64-49);
    }
    lottId = LOTTERY_PLAY_METHOD_FOOTBALL;
    [self refresh2];
//    [self.navigationItem setTitle:@"竞彩足球"];
    
    //添加下拉选择
    [self addMenuBtn];
    selectLotteryList = [[NSMutableArray alloc] initWithObjects:@"让球胜平负", @"胜平负", @"总进球", @"比分", @"半全场", @"混合过关", nil];
    //初始化选择全部
    [self initSelectFirstTitle];
}

-(void)initSelectFirstTitle
{
    NSString *rBtnTitle = [rBtn titleForState:UIControlStateNormal];
    NSInteger selectRow = [selectLotteryList indexOfObject:rBtnTitle];
    self.lastIndexPath = [NSIndexPath indexPathForRow:selectRow inSection:0];
}

-(void)addMenuBtn
{
    rv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-130, 30)];
    rBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rBtn addTarget:self action:@selector(selectLottery) forControlEvents:UIControlEventTouchUpInside];
    [rBtn setTitle:@"让球胜平负" forState:UIControlStateNormal];
    rBtn.titleLabel.font = [UIFont systemFontOfSize: 19.0];
    [rBtn setFrame:CGRectMake(0, 2, 180, 19)];
    rBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    UIImage *rBtnImg = LOADIMAGE(@"navBar_down");
    rImv = [[UIImageView alloc] initWithImage:rBtnImg];
    [self setRightBtnImage:@"让球胜平负"];
    
    //创建的一个view，加入btn和图片
    [rv addSubview: rBtn];
    [rv addSubview:rImv];
    self.navigationItem.titleView = rv;
    
    //加入手势
    rImv.userInteractionEnabled = YES;
    UITapGestureRecognizer *recognizer=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectLottery)];
    [rImv addGestureRecognizer:recognizer];
}
//计算rImv的坐标
-(void)setRightBtnImage:(NSString *)titleStr
{
    JddSportNumber *btntitle = [[JddSportNumber alloc] init];
    btntitle.titleStr = titleStr;
    CGFloat width = [btntitle customWidth:19 font:19];
    rBtn.center = CGPointMake(90, 15);
    CGRect frame = rBtn.frame;
    frame.origin.x = (rv.width - width - 17) / 2;
    frame.size.width = width;
    rBtn.frame = frame;
    [rImv setFrame:CGRectMake(rBtn.frame.origin.x + width + 3, 10, 14, 10)];
}

//设置彩种，后进行刷新数据
- (void)setLotteryContent:(NSInteger)tag{
    
    
    _floatLayerIndex = tag;
    [_layer loadFloatLayer:selectLotteryList withIndex:_floatLayerIndex];
    NSString *title = [selectLotteryList objectAtIndex:_floatLayerIndex];
    [self setRbtnTitle:title];
    //下拉箭头跟在彩种的后面
    [self setRightBtnImage:title];
}

-(void)selectLottery
{
    
    if (!_layer) {
        _layer = [[FloatLayer alloc] initWithFloatLayer:FloatLayerTogetherBuy withLayerCallBack:^(NSInteger index) {
            [self setLotteryContent:index];
        }];
    }
    
    [_layer loadFloatLayer:selectLotteryList withIndex:_floatLayerIndex];
    // create the alert
    /*
	self.alert = [MLTableAlert tableAlertWithTitle:@"请选择" cancelButtonTitle:@"取消" numberOfRows:^NSInteger (NSInteger section)
                  {
                  return selectLotteryList.count;
                  }
                                          andCells:^UITableViewCell* (MLTableAlert *anAlert, NSIndexPath *indexPath)
                  {
                  NSInteger row = indexPath.row;
                  static NSString *CellIdentifier = @"CellIdentifier";
                  UITableViewCell *cell = [anAlert.table dequeueReusableCellWithIdentifier:CellIdentifier];
                  if (cell == nil)
                      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                  cell.textLabel.text = [selectLotteryList objectAtIndex:row];
                  cell.textLabel.font = [UIFont systemFontOfSize:16];
                  NSUInteger oldRow = [self.lastIndexPath row];
                  cell.accessoryType = (row == oldRow && self.lastIndexPath != nil) ?
                  UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;
                  return cell;
                  }];
	
	// Setting custom alert height
	self.alert.height = 350;
    self.alert.lastIndexPath = self.lastIndexPath;
    // configure actions to perform
	[self.alert configureSelectionBlock:^(NSIndexPath *selectedIndex){
        self.lastIndexPath = self.alert.lastIndexPath;
        //得到alert的tableVew的显示位置
        self.alertTableViewContentOffset = self.alert.table.contentOffset;
        NSString *title = [selectLotteryList objectAtIndex:selectedIndex.row];
        [self setRbtnTitle:title];
        //下拉箭头跟在彩种的后面
        [self setRightBtnImage:title];
	} andCompletionBlock:^{
		
	}];
	
	// show the alert
	[self.alert show];
    //设置alert的tableVew的显示位置
    [self.alert.table setContentOffset:self.alertTableViewContentOffset animated:NO];
     */
}

//选择彩种
-(void)setRbtnTitle:(NSString *)title
{
    [rBtn setTitle:title forState:UIControlStateNormal];
    NSInteger row =  [selectLotteryList indexOfObject:title];
    lottId = [JddCommonFunction getSportLottIdWithLotteryNameIndex:row];
    [self clearSelect:nil];
}

-(void)addChildTableViewWithResultStr:(NSString *)resultStr
{
    childTableview = [[JddPickNumSportTableView alloc] init];
    childTableview.sResult = resultStr;
    childTableview.delegate = self;
    [self addChildViewController:childTableview];
    [tView addSubview:childTableview.view];
    [self clearSelect:nil];
}

-(IBAction)clearSelect:(id)sender{
    childTableview.lottId = lottId;
    [childTableview.sportlotterylist.sportList removeAllObjects];
    [childTableview refreshTableView];
    self.label3.text = @"---";
    self.label2.text = @"已选择0场比赛，截止时间:";
}

- (void)QuerySportLotteryIssueOperationResult:(NSData *)result{
    if (result) {
        NSString *resultStr = [JddDataParser parseSportLotteryIssueResult:result];
        [self addChildTableViewWithResultStr:resultStr];
    }   
    [JddCommonFunction setWaitingViewHidden:YES fromController:self];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"JCZQ"];
	[MobClick event:@"Lottery-JCZQ"];

    [self setNavigationBarHidden:NO];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"JCZQ"];
}
-(void)refresh2
{
    [JddCommonFunction setWaitingViewHidden:NO fromController:self];
    JddQuerySportLotteryIssueOperation *operation4 = [[JddQuerySportLotteryIssueOperation alloc] init];
    operation4.delegate = self;
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation4];
    
}

-(void)selectMatch:(NSString *)text2 :(NSString *)text3
{
    self.label2.text = text2;
    self.label3.text = text3;
}

@end
